package com.zhang.common.db;

import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import com.zhang.common.config.MybatisPlusConfig;
import com.zhang.common.config.MybatisProperties;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 多数据源配置
 *
 * 不管管注解是sqlSessionFactoryRef还是sqlSessionTemplateRef，在使用的时候走的都是sqlSessionTemplate
 * 使用sqlSessionTemplateRef = "xxSqlSessionTemplate" 注解即可
 * @author zhangxin
 * @date 2021/5/20
 */
@Configuration
@MapperScan(basePackages = "com.zhang.common.mapper.read", sqlSessionTemplateRef = "mybatisPlusSqlSessionTemplate")
public class MybatisPlusDataSourceConfig {

    @Autowired
    private ExtraDataSourceBuilder extraDataSourceBuilder;

    @Autowired
    private MybatisPlusConfig mybatisPlusConfig;


    @Autowired
    private MybatisProperties mybatisProperties;

    /**
     * 指定数据库
     *
     * @return
     * @throws Exception
     */
    @Bean(name = "mybatisPlusSqlSessionFactory")
    public SqlSessionFactory mybatisPlusSqlSessionFactory() throws Exception {
        // 非mybatis配置
        // final SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();
        // ......
        // mybatis配置
        final MybatisSqlSessionFactoryBean mybatisSqlSessionFactoryBean = new MybatisSqlSessionFactoryBean();
        mybatisSqlSessionFactoryBean.setDataSource(extraDataSourceBuilder.build());
        // mybatisPlus的分页插件
        mybatisSqlSessionFactoryBean.setPlugins(mybatisPlusConfig.mybatisPlusInterceptor());
        mybatisSqlSessionFactoryBean.setMapperLocations(this.getMybatisPlusMapperLocations());
        return mybatisSqlSessionFactoryBean.getObject();
    }

    /**
     * 指定数据库
     *
     * @return
     * @throws Exception
     */
    @Bean(name = "mybatisPlusSqlSessionTemplate")
    public SqlSessionTemplate mybatisPlusSqlSessionTemplate() throws Exception {
        return new SqlSessionTemplate(this.mybatisPlusSqlSessionFactory());
    }

    /**
     * 事务支持
     *
     * @return
     * @throws Exception
     */
    @Bean(name = "mybatisPlusTransactionManager")
    public DataSourceTransactionManager mybatisPlusTransactionManager() {
        return new DataSourceTransactionManager(extraDataSourceBuilder.build());
    }


    private Resource[] getMybatisPlusMapperLocations() throws IOException {
        PathMatchingResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
        List<Resource> resources = new ArrayList<>();

        String[] mapperLocations = mybatisProperties.getMapperLocations();
        if (null != mapperLocations) {
            for (String mapperLocation : mybatisProperties.getMapperLocations()) {
                // 指定mapper目录
                if (mapperLocation.contains(extraDataSourceBuilder.getMapperDir())) {
                    Resource[] mappers = resourcePatternResolver.getResources(mapperLocation);
                    resources.addAll(Arrays.asList(mappers));
                }
            }
        }
        return resources.toArray(new Resource[resources.size()]);
    }

}
